<template>
    <view class="ai-doctor-container">
        <!-- 顶部导航 -->
        <view class="nav-header">
            <view class="nav-back" @click="goBack">
                <text class="iconfont icon-arrow-left"></text>
            </view>
            <view class="nav-title">AI智能医生</view>
            <view class="nav-menu" @click="showMenu">
                <text class="iconfont icon-menu"></text>
            </view>
        </view>



        <!-- 聊天区域 -->
        <view class="chat-container">
            <scroll-view class="chat-messages" scroll-y="true" :scroll-top="scrollTop" scroll-with-animation="true">
                <view class="message-item" v-for="(message, index) in messages" :key="index">
                    <view class="message-wrapper" :class="message.role === 'user' ? 'user-message' : 'ai-message'">
                        <!-- AI医生头像 -->
                        <image v-if="message.role !== 'user'" class="avatar" src="/static/image/ai-doctor.png"
                            mode="aspectFit"></image>

                        <!-- 消息内容 -->
                        <view class="message-content" :class="message.role === 'user' ? 'user-content' : 'ai-content'">
                            <!-- 普通文本消息 -->
                            <text class="message-text"
                                v-if="!isAppointmentMessage(message.content) && !hasButtons(message.content)">{{
                                    message.content }}</text>

                            <!-- 带按钮的AI消息 -->
                            <view v-if="hasButtons(message.content) && message.role !== 'user'"
                                class="ai-message-with-buttons">
                                <!-- 特殊处理时间选择页面 -->
                                <view v-if="isTimeSelectionMessage(message.content)" class="time-selection-container">
                                    <text class="message-text">{{ getTimeSelectionHeader(message.content) }}</text>

                                    <!-- 按日期分组显示时间段 -->
                                    <view v-for="(dateGroup, dateKey) in getTimeSlotsByDate(message.content)"
                                        :key="dateKey" class="date-group">
                                        <text class="date-header">📅 {{ dateKey }}</text>

                                        <view class="time-slots-group" v-if="dateGroup.length > 0">
                                            <view v-for="(button, index) in dateGroup" :key="index"
                                                class="time-slot-button"
                                                @click="handleButtonClick(button.text, button.action)">
                                                <text class="time-slot-text">{{ button.timeDisplay }}</text>
                                            </view>
                                        </view>

                                        <text v-else class="no-slots">❌ 当天无可用号源</text>
                                    </view>

                                    <!-- 其他操作按钮 -->
                                    <view class="button-group">
                                        <view v-for="(button, index) in getNonTimeSlotButtons(message.content)"
                                            :key="index" class="action-button"
                                            @click="handleButtonClick(button.text, button.action)">
                                            <text class="button-text">{{ button.text }}</text>
                                        </view>
                                    </view>
                                </view>

                                <!-- 普通消息显示 -->
                                <view v-else>
                                    <text class="message-text">{{ getMessageText(message.content) }}</text>

                                    <!-- 按钮组 -->
                                    <view class="button-group">
                                        <view v-for="(button, index) in getButtons(message.content)" :key="index"
                                            class="action-button"
                                            @click="handleButtonClick(button.text, button.action)">
                                            <text class="button-text">{{ button.text }}</text>
                                        </view>
                                    </view>
                                </view>
                            </view>

                            <!-- 预约信息卡片 -->
                            <appointment-card v-if="isAppointmentMessage(message.content)"
                                :appointmentData="message.content" @book-appointment="handleBookAppointment">
                            </appointment-card>

                            <text class="message-time">{{ message.timestamp }}</text>
                        </view>

                        <!-- 用户头像 -->
                        <image v-if="message.role === 'user'" class="avatar" src="/static/image/user-avatar.png"
                            mode="aspectFit"></image>
                    </view>
                </view>

                <!-- 正在输入提示 -->
                <view class="typing-indicator" v-if="isTyping">
                    <image class="avatar" src="/static/image/ai-doctor.png" mode="aspectFit"></image>
                    <view class="typing-content">
                        <view class="typing-dots">
                            <view class="dot"></view>
                            <view class="dot"></view>
                            <view class="dot"></view>
                        </view>
                        <text class="typing-text">AI医生正在思考...</text>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 智能功能区 -->
        <smart-actions :userId="userId" @smart-action="handleSmartAction" v-if="!isTyping && messages.length > 1">
        </smart-actions>

        <!-- 快捷回复 -->
        <view class="quick-replies" v-if="quickReplies.length > 0">
            <scroll-view class="replies-scroll" scroll-x="true">
                <view class="reply-item" v-for="(reply, index) in quickReplies" :key="index"
                    @click="sendQuickReply(reply)">
                    <text class="reply-text">{{ reply }}</text>
                </view>
            </scroll-view>
        </view>

        <!-- 输入区域 -->
        <view class="input-container">
            <view class="input-wrapper">
                <input class="message-input" type="text" v-model="inputMessage" placeholder="描述您的症状或问题..."
                    placeholder-class="input-placeholder" @confirm="sendMessage" :disabled="isTyping" />
                <view class="send-button" @click="sendMessage"
                    :class="{ 'disabled': !inputMessage.trim() || isTyping }">
                    <text class="iconfont icon-send"></text>
                </view>
            </view>
        </view>

        <!-- 功能菜单弹窗 -->
        <view v-if="showMenuPopup" class="popup-overlay" @click="closeMenu">
            <view class="menu-container" @click.stop="">
                <view class="menu-item" @click="viewHistory">
                    <text class="iconfont icon-history"></text>
                    <text class="menu-text">对话历史</text>
                </view>
                <view class="menu-item" @click="closeMenu">
                    <text class="iconfont icon-close"></text>
                    <text class="menu-text">关闭</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapState } from 'vuex'
import SmartActions from '@/components/ai-doctor/SmartActions.vue'

export default {
    components: {
        SmartActions
    },
    data() {
        return {
            inputMessage: '',
            messages: [],
            isTyping: false,
            scrollTop: 0,
            memoryId: '',
            recentDoctors: [],
            showMenuPopup: false,
            quickReplies: [
                '推荐一些感冒药',
                '头痛怎么办',
                '发烧了该吃什么药'
            ],
            currentStreamMessage: '', // 当前正在接收的流式消息
            streamMessageIndex: -1, // 流式消息在messages数组中的索引
        }
    },
    computed: {
        ...mapState(['userId', 'userName'])
    },
    onLoad() {
        this.initChat();
        this.loadRecentDoctors();
    },
    methods: {
        initChat() {
            // 生成唯一的会话ID
            this.memoryId = `ai_doctor_${this.userId}_${Date.now()}`;

            // 初始化欢迎消息
            this.addMessage('assistant', '👋 您好！我是AI智能医生助手。\n\n我可以帮助您：\n• 🔍 根据症状匹配科室和医生\n• 📅 智能预约挂号\n• 💊 推荐非处方药物\n• ❌ 取消现有预约\n• 💬 提供健康咨询\n\n请描述您的症状或需求，我会为您提供专业建议。');
        },

        async loadRecentDoctors() {
            try {
                const params = new URLSearchParams({ memoryId: this.memoryId }).toString();
                const requestUrl = `/ai-doctor/recent-doctors?${params}`;
                console.log('🚀 准备请求URL:', requestUrl);

                const res = await new Promise((resolve, reject) => {
                    uni.request({
                        url: requestUrl,
                        method: 'GET',
                        header: {
                            'Content-Type': 'application/json'
                        },
                        success: (response) => {
                            console.log('✅ 请求成功 - 状态码:', response.statusCode);
                            console.log('✅ 请求成功 - 响应数据:', response.data);
                            if (response.statusCode === 200) {
                                resolve(response.data);
                            } else {
                                console.error('❌ 状态码非200:', response.statusCode, response);
                                reject(response);
                            }
                        },
                        fail: (err) => {
                            console.error('❌ 请求完全失败:', err);
                            console.log('🔍 请求URL:', requestUrl);
                            console.log('🔍 错误详情:', JSON.stringify(err, null, 2));
                            reject(err);
                        }
                    });
                });

                if (res.code === 200) {
                    this.recentDoctors = res.data.map((doctor, index) => ({
                        name: doctor.name || doctor.doctorName || `医生${index + 1}`,
                        specialty: doctor.specialty || doctor.doctorSpecialty || '未知科室',
                        description: doctor.description || '医生简介',
                        rating: doctor.rating || 0,
                        lastTime: doctor.lastChatTime || '最近交流',
                        info: doctor
                    }));
                }
            } catch (error) {
                console.error('加载最近医生失败', error);
            }
        },

        async sendMessage() {
            if (!this.inputMessage.trim() || this.isTyping) return;

            const message = this.inputMessage.trim();
            this.inputMessage = '';

            // 添加用户消息
            this.addMessage('user', message);

            // 开始接收AI回复
            this.startStreamingResponse(message);
        },

        async startStreamingResponse(message) {
            this.isTyping = true;
            this.currentStreamMessage = '';

            // 预先添加一个空的AI消息，用于流式更新
            this.addMessage('assistant', '');
            this.streamMessageIndex = this.messages.length - 1;

            try {
                // 构建请求URL
                const params = new URLSearchParams({
                    memoryId: this.memoryId,
                    message: message,
                    userId: this.userId || 1
                });

                const url = `/ai-doctor/chat?${params.toString()}`;

                // 使用uni.request进行请求
                const result = await new Promise((resolve, reject) => {
                    uni.request({
                        url: url,
                        method: 'POST',
                        header: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        success: (response) => {
                            console.log('响应状态码:', response.statusCode);
                            console.log('响应数据:', response.data);
                            if (response.statusCode === 200) {
                                resolve(response.data);
                            } else {
                                reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage || '请求失败'}`));
                            }
                        },
                        fail: (err) => {
                            console.error('请求失败:', err);
                            reject(new Error(`网络请求失败: ${err.errMsg || '未知错误'}`));
                        }
                    });
                });

                console.log('AI响应结果:', result);

                if (result.code === 200 && result.data) {
                    // 更新UI中的消息
                    this.updateStreamMessage(result.data);
                } else {
                    throw new Error(result.msg || 'AI响应失败');
                }

            } catch (error) {
                console.error('AI医生对话失败', error);
                this.updateStreamMessage('抱歉，AI医生暂时无法响应，请稍后重试。');
            } finally {
                this.isTyping = false;
                this.currentStreamMessage = '';
                this.streamMessageIndex = -1;
            }
        },

        updateStreamMessage(content) {
            if (this.streamMessageIndex >= 0 && this.streamMessageIndex < this.messages.length) {
                this.messages[this.streamMessageIndex].content = content;
                this.messages[this.streamMessageIndex].timestamp = this.formatTime(new Date());
                // 触发视图更新
                this.$forceUpdate();
            }
        },

        sendQuickReply(reply) {
            this.inputMessage = reply;
            this.sendMessage();
        },

        addMessage(role, content) {
            const message = {
                role: role,
                content: content,
                timestamp: this.formatTime(new Date())
            };
            this.messages.push(message);
            this.$nextTick(() => {
                this.scrollToBottom();
            });
        },

        scrollToBottom() {
            this.$nextTick(() => {
                this.scrollTop = this.scrollTop === 99999 ? 99998 : 99999;
            });
        },

        formatTime(date) {
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${hours}:${minutes}`;
        },

        goBack() {
            uni.navigateBack();
        },

        showMenu() {
            this.showMenuPopup = true;
        },

        closeMenu() {
            this.showMenuPopup = false;
        },

        async clearHistory() {
            try {
                await new Promise((resolve, reject) => {
                    uni.request({
                        url: `/ai-doctor/history`,
                        method: 'DELETE',
                        data: { memoryId: this.memoryId },
                        header: {
                            'Content-Type': 'application/json'
                        },
                        success: (response) => {
                            if (response.statusCode === 200) {
                                resolve(response.data);
                            } else {
                                reject(response);
                            }
                        },
                        fail: (err) => {
                            reject(err);
                        }
                    });
                });

                this.messages = [];
                this.initChat();
                this.closeMenu();

                uni.showToast({
                    title: '对话历史已清除',
                    icon: 'success'
                });
            } catch (error) {
                console.error('清除历史失败', error);
                uni.showToast({
                    title: '清除失败',
                    icon: 'none'
                });
            }
        },

        viewHistory() {
            this.closeMenu();
            uni.navigateTo({
                url: `/pages/doctor/chat-history?memoryId=${this.memoryId}`
            });
        },

        viewDoctorHistory(doctor) {
            console.log('查看医生历史', doctor);
            // 这里可以实现查看特定医生的对话历史
        },

        // 处理智能功能操作
        handleSmartAction(action) {
            console.log('智能功能操作', action);
            if (action.type === 'smart-appointment') {
                this.inputMessage = action.message;
                this.sendMessage();
            } else if (action.type === 'view-appointments') {
                this.inputMessage = action.message;
                this.sendMessage();
            } else if (action.type === 'recommend-medicine') {
                this.inputMessage = action.message;
                this.sendMessage();
            } else if (action.type === 'cancel-appointment') {
                // 直接显示取消预约的结果
                this.addMessage('assistant', action.message);
            }
        },

        // 处理预约预约
        async handleBookAppointment(bookingData) {
            console.log('预约数据', bookingData);

            try {
                const res = await new Promise((resolve, reject) => {
                    uni.request({
                        url: `/ai-doctor/book`,
                        method: 'POST',
                        data: {
                            doctorName: bookingData.doctorName,
                            appointmentTime: bookingData.appointmentTime,
                            userId: this.userId || 1
                        },
                        header: {
                            'Content-Type': 'application/json'
                        },
                        success: (response) => {
                            if (response.statusCode === 200) {
                                resolve(response.data);
                            } else {
                                reject(response);
                            }
                        },
                        fail: (err) => {
                            reject(err);
                        }
                    });
                });

                if (res.code === 200) {
                    this.addMessage('assistant', res.data);
                    uni.showToast({
                        title: '预约处理完成',
                        icon: 'success'
                    });
                } else {
                    this.addMessage('assistant', '预约失败，请稍后重试');
                    uni.showToast({
                        title: '预约失败',
                        icon: 'none'
                    });
                }
            } catch (error) {
                console.error('预约失败', error);
                this.addMessage('assistant', '预约过程中出现错误，请稍后重试');
                uni.showToast({
                    title: '预约失败',
                    icon: 'none'
                });
            }
        },

        // 判断是否为预约消息
        isAppointmentMessage(content) {
            return content && (
                content.includes('👨‍⚕️') && content.includes('医生') ||
                content.includes('可预约时间') ||
                content.includes('近3天') && content.includes('医生')
            );
        },

        // 检查消息是否包含按钮
        hasButtons(content) {
            return content && content.includes && content.includes('[') && content.includes(']');
        },

        // 提取消息文本（去除按钮部分）
        getMessageText(content) {
            if (!content) return '';

            // 特殊处理时间选择内容
            if (content.includes('时间选择') && content.includes('📅')) {
                // 保留日期和时间段信息，但移除按钮格式
                let text = content;
                // 将按钮格式转换为普通文本显示
                text = text.replace(/🔸\s*\[选择时间:([^\]]+)\]\s*-\s*([^\n]+)/g, '    • $2');
                text = text.replace(/🔸\s*\[([^\]]+)\]\s*-\s*([^\n]+)/g, '');
                return text.trim();
            }

            // 移除按钮标记，只保留文本
            return content.replace(/🔸\s*\[([^\]]+)\][^\n]*/g, '').trim();
        },

        // 解析按钮
        getButtons(content) {
            if (!content) return [];

            const buttons = [];
            // 匹配 🔸 [按钮文字] - 描述 格式
            const buttonRegex = /🔸\s*\[([^\]]+)\](?:\s*-\s*([^\n]+))?/g;
            let match;

            while ((match = buttonRegex.exec(content)) !== null) {
                const buttonText = match[1];

                // 特殊处理：如果是时间选择页面，要分别处理时间段按钮和其他按钮
                if (content.includes('时间选择') && content.includes('📅')) {
                    // 如果是时间段按钮，放在时间段区域
                    if (buttonText.startsWith('选择时间:')) {
                        buttons.push({
                            text: buttonText,
                            action: buttonText,
                            description: match[2] || '',
                            isTimeSlot: true
                        });
                    } else {
                        // 其他按钮（如开始预约、返回主菜单）正常处理
                        buttons.push({
                            text: buttonText,
                            action: buttonText,
                            description: match[2] || '',
                            isTimeSlot: false
                        });
                    }
                } else {
                    // 普通页面，正常处理所有按钮
                    buttons.push({
                        text: buttonText,
                        action: buttonText,
                        description: match[2] || ''
                    });
                }
            }

            return buttons;
        },

        // 判断是否为时间选择消息
        isTimeSelectionMessage(content) {
            return content && content.includes('时间选择') && content.includes('📅');
        },

        // 获取时间选择页面的标题部分
        getTimeSelectionHeader(content) {
            if (!content) return '';
            const lines = content.split('\n');
            // 只保留第一行标题
            return lines[0] || '';
        },

        // 按日期分组获取时间段
        getTimeSlotsByDate(content) {
            if (!content) return {};

            const dateGroups = {};
            // 匹配新格式: 🔸 [时间段:14:30|595|09-01 (周一)] - 14:30 预约
            const timeSlotRegex = /🔸\s*\[时间段:([^|]+)\|(\d+)\|([^\]]+)\]\s*-\s*([^\n]+)/g;
            let match;

            while ((match = timeSlotRegex.exec(content)) !== null) {
                const timeDisplay = match[1]; // "14:30"
                const appointmentId = match[2]; // "595"
                const dateKey = match[3]; // "09-01 (周一)"
                const description = match[4]; // "14:30 预约"

                if (!dateGroups[dateKey]) {
                    dateGroups[dateKey] = [];
                }

                dateGroups[dateKey].push({
                    text: `时间段:${timeDisplay}|${appointmentId}|${dateKey}`,
                    action: `时间段:${timeDisplay}|${appointmentId}|${dateKey}`,
                    timeDisplay: timeDisplay,
                    appointmentId: appointmentId,
                    dateKey: dateKey,
                    description: description
                });
            }

            // 按照时间排序每个日期的时间段
            Object.keys(dateGroups).forEach(dateKey => {
                dateGroups[dateKey].sort((a, b) => a.timeDisplay.localeCompare(b.timeDisplay));
            });

            return dateGroups;
        },

        // 获取时间段按钮
        getTimeSlotButtons(content) {
            if (!content) return [];
            const timeSlotButtons = [];
            const buttonRegex = /🔸\s*\[选择时间:([^\]]+)\]\s*-\s*([^\n]+)/g;
            let match;

            while ((match = buttonRegex.exec(content)) !== null) {
                const timeData = match[1]; // 格式: "14:30|595"
                const [timeDisplay, appointmentId] = timeData.split('|');

                timeSlotButtons.push({
                    text: `选择时间:${timeData}`,
                    action: `选择时间:${timeData}`,
                    timeDisplay: timeDisplay,
                    appointmentId: appointmentId,
                    description: match[2] || ''
                });
            }

            return timeSlotButtons;
        },

        // 获取非时间段按钮
        getNonTimeSlotButtons(content) {
            if (!content) return [];
            const otherButtons = [];
            const buttonRegex = /🔸\s*\[([^\]]+)\](?:\s*-\s*([^\n]+))?/g;
            let match;

            while ((match = buttonRegex.exec(content)) !== null) {
                const buttonText = match[1];
                // 排除时间段按钮（新格式和旧格式都排除）
                if (!buttonText.startsWith('选择时间:') && !buttonText.startsWith('时间段:')) {
                    otherButtons.push({
                        text: buttonText,
                        action: buttonText,
                        description: match[2] || ''
                    });
                }
            }

            return otherButtons;
        },

        // 处理按钮点击
        handleButtonClick(buttonText, action) {
            console.log('按钮点击:', buttonText, action);

            // 将按钮文字作为用户消息发送
            this.addMessage('user', buttonText);

            // 发送到AI处理
            this.sendAIMessage(buttonText);
        },

        // 发送AI消息（独立方法）
        async sendAIMessage(message) {
            this.isTyping = true;
            this.currentStreamMessage = '';

            // 预先添加一个空的AI消息，用于更新
            this.addMessage('assistant', '');
            this.streamMessageIndex = this.messages.length - 1;

            try {
                // 构建请求URL
                const params = new URLSearchParams({
                    memoryId: this.memoryId,
                    message: message,
                    userId: this.userId || 1
                });

                const url = `/ai-doctor/chat?${params.toString()}`;

                // 使用uni.request进行请求
                const result = await new Promise((resolve, reject) => {
                    uni.request({
                        url: url,
                        method: 'POST',
                        header: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        success: (response) => {
                            console.log('响应状态码:', response.statusCode);
                            console.log('响应数据:', response.data);
                            if (response.statusCode === 200) {
                                resolve(response.data);
                            } else {
                                reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage || '请求失败'}`));
                            }
                        },
                        fail: (err) => {
                            console.error('请求失败:', err);
                            reject(new Error(`网络请求失败: ${err.errMsg || '未知错误'}`));
                        }
                    });
                });

                console.log('AI响应结果:', result);

                if (result.code === 200 && result.data) {
                    // 更新UI中的消息
                    this.updateStreamMessage(result.data);
                } else {
                    throw new Error(result.msg || 'AI响应失败');
                }

            } catch (error) {
                console.error('AI医生对话失败', error);
                this.updateStreamMessage('抱歉，AI医生暂时无法响应，请稍后重试。');
            } finally {
                this.isTyping = false;
                this.currentStreamMessage = '';
                this.streamMessageIndex = -1;
            }
        }
    }
}
</script>

<style lang="scss">
page {
    height: 100%;
    background-color: #f5f5f5;
}

.ai-doctor-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
}

.nav-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;

    .nav-back,
    .nav-menu {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.1);
    }

    .nav-title {
        font-size: 36rpx;
        font-weight: bold;
    }
}

.recent-doctors {
    background: white;
    margin: 20rpx;
    border-radius: 20rpx;
    padding: 30rpx;

    .section-title {
        margin-bottom: 20rpx;

        .title-text {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
        }
    }

    .doctors-scroll {
        white-space: nowrap;

        .doctor-item {
            display: inline-block;
            margin-right: 30rpx;
            text-align: center;
            padding: 20rpx;
            border-radius: 15rpx;
            background: #f8f9fa;
            min-width: 150rpx;

            .doctor-avatar {
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
                margin-bottom: 10rpx;
            }

            .doctor-name {
                display: block;
                font-size: 28rpx;
                color: #333;
                margin-bottom: 5rpx;
            }

            .doctor-time {
                display: block;
                font-size: 24rpx;
                color: #666;
            }
        }
    }
}

.chat-container {
    flex: 1;
    padding: 0 20rpx;

    .chat-messages {
        height: 100%;

        .message-item {
            margin-bottom: 30rpx;

            .message-wrapper {
                display: flex;
                align-items: flex-end;

                &.user-message {
                    justify-content: flex-end;
                }

                &.ai-message {
                    justify-content: flex-start;
                }
            }

            .avatar {
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
                margin: 0 20rpx;
            }

            .message-content {
                max-width: 70%;
                padding: 25rpx 30rpx;
                border-radius: 20rpx;
                position: relative;

                &.user-content {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                }

                &.ai-content {
                    background: white;
                    color: #333;
                    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
                }

                .message-text {
                    display: block;
                    font-size: 30rpx;
                    line-height: 1.5;
                    word-break: break-word;
                    white-space: pre-wrap;
                }

                .message-time {
                    display: block;
                    font-size: 24rpx;
                    opacity: 0.7;
                    margin-top: 10rpx;
                }
            }
        }
    }
}

.typing-indicator {
    display: flex;
    align-items: flex-end;
    margin-bottom: 30rpx;

    .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
    }

    .typing-content {
        background: white;
        border-radius: 20rpx;
        padding: 25rpx 30rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

        .typing-dots {
            display: flex;
            gap: 8rpx;
            margin-bottom: 10rpx;

            .dot {
                width: 12rpx;
                height: 12rpx;
                border-radius: 50%;
                background: #666;
                animation: typing 1.4s infinite;

                &:nth-child(2) {
                    animation-delay: 0.2s;
                }

                &:nth-child(3) {
                    animation-delay: 0.4s;
                }
            }
        }

        .typing-text {
            font-size: 26rpx;
            color: #666;
        }
    }
}

@keyframes typing {

    0%,
    60%,
    100% {
        opacity: 0.3;
        transform: scale(0.8);
    }

    30% {
        opacity: 1;
        transform: scale(1);
    }
}

.quick-replies {
    padding: 20rpx;
    background: white;

    .replies-scroll {
        white-space: nowrap;

        .reply-item {
            display: inline-block;
            margin-right: 20rpx;
            padding: 15rpx 30rpx;
            background: #f8f9fa;
            border-radius: 30rpx;
            border: 1rpx solid #e9ecef;

            .reply-text {
                font-size: 28rpx;
                color: #666;
            }
        }
    }
}

.input-container {
    background: white;
    padding: 20rpx;
    border-top: 1rpx solid #eee;

    .input-wrapper {
        display: flex;
        align-items: center;
        background: #f8f9fa;
        border-radius: 50rpx;
        padding: 10rpx 20rpx;

        .message-input {
            flex: 1;
            height: 80rpx;
            font-size: 30rpx;
            background: transparent;
        }

        .input-placeholder {
            color: #999;
        }

        .send-button {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 20rpx;

            &.disabled {
                opacity: 0.5;
            }

            .iconfont {
                color: white;
                font-size: 36rpx;
            }
        }
    }
}

// 弹窗遮罩层
.popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: flex-start;
    z-index: 1000;
    padding-top: 100rpx;
}

.menu-container {
    background: white;
    border-radius: 20rpx;
    padding: 40rpx;
    margin: 0 40rpx;
    max-width: 600rpx;
    width: 100%;

    .menu-item {
        display: flex;
        align-items: center;
        padding: 30rpx 0;
        border-bottom: 1rpx solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }

        .iconfont {
            font-size: 40rpx;
            color: #666;
            margin-right: 30rpx;
        }

        .menu-text {
            font-size: 32rpx;
            color: #333;
        }
    }
}

// 按钮组样式
.ai-message-with-buttons {
    .message-text {
        margin-bottom: 20rpx;
    }

    .button-group {
        display: flex;
        flex-direction: column;
        gap: 15rpx;
        margin-top: 20rpx;

        .action-button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 25rpx;
            padding: 20rpx 30rpx;
            margin: 5rpx 0;
            box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.3);
            transition: all 0.3s ease;

            &:active {
                transform: scale(0.95);
                box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.4);
            }

            .button-text {
                color: white;
                font-size: 28rpx;
                font-weight: 500;
                text-align: center;
                display: block;
            }

            // 不同类型按钮的颜色
            &:nth-child(odd) {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            }

            &:nth-child(even) {
                background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            }

            // 特殊按钮样式
            &:first-child {
                background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            }
        }
    }
}

// 响应式布局 - 按钮在小屏幕上堆叠，大屏幕上可以横向排列
@media (min-width: 750rpx) {
    .button-group {
        flex-direction: row;
        flex-wrap: wrap;

        .action-button {
            flex: 1;
            min-width: 200rpx;
            margin: 5rpx;
        }
    }
}

/* 时间选择特殊样式 */
.time-selection-container {
    width: 100%;
}

.date-group {
    margin: 24rpx 0;
    padding: 16rpx;
    background: #f8f9ff;
    border-radius: 16rpx;
    border: 1px solid #e6e8ff;
}

.date-header {
    font-size: 32rpx;
    font-weight: 600;
    color: #667eea;
    margin-bottom: 16rpx;
    display: block;
}

.time-slots-group {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
    margin: 16rpx 0;
    padding: 0;
}

.no-slots {
    font-size: 28rpx;
    color: #999;
    text-align: center;
    padding: 20rpx;
    display: block;
}

.time-slot-button {
    flex: 0 0 auto;
    min-width: 160rpx;
    padding: 20rpx 32rpx;
    margin: 8rpx;
    border-radius: 40rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-size: 28rpx;
    font-weight: 500;
    text-align: center;
    box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
}

.time-slot-button:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 6rpx rgba(102, 126, 234, 0.5);
}

.time-slot-text {
    color: white;
    font-size: 28rpx;
    font-weight: 500;
}
</style>
